import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import cart from './modules/cart'
import products from './modules/products'
import VuexPersistence from 'vuex-persist'
import createLogger from 'vuex/dist/logger'
import localforage from 'localforage'
import VuexPersistPatch from './plugins/vuex-persist-patch'

const RESTORE_MUTATION = 'RESTORE_MUTATION'

localforage.config({
  driver: localforage.INDEXEDDB,
  name: 'myApp',
  version: 1.0,
  size: 4980736,
  storeName: 'keyvaluepairs',
  description: 'some description'
});

const vuexLocal = new VuexPersistence({
  // storage: window.sessionStorage,
  key: 'key',
  strictMode: true,
  // 只保存 cart
  // modules: ['cart'],
  // 只保存products 作用大于modules  reducer和modules 不同时用
  reducer: state => ({
    count: state.count,
    cart: state.cart,
  }),
  filter: (mutation) => (
    // 过滤掉没有 mutation.type 对应的操作就不会起作用
    mutation.type === 'ADD_TO_CART'
    // mutation.type === 'SET_CART_ITEMS'
  ),
  asyncStorage: true,
  storage: localforage
})

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  state: {
    count: 0
  },
  actions,
  mutations: {
    [RESTORE_MUTATION]: vuexLocal.RESTORE_MUTATION
  },
  modules: {
    cart,
    products
  },
  strict: debug,
  plugins: debug ? [
    createLogger(),
    vuexLocal.plugin,
    VuexPersistPatch(),
  ] : [
      vuexLocal.plugin,
      VuexPersistPatch()
    ]
})